import 'dart:async';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/model/slave_ems_network_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/base_detail_controller/base_detail_controller.dart';
import 'package:yt_devops/pages/devices/device_tab/model/device_item_model.dart';
import 'package:yt_devops/pages/devices/device_tab/model/device_items_group_model.dart';
import 'package:yt_devops/pages/devices/device_tab/utils/device_func_util.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/tabs/device_tab/device_tab_controller.dart';
import 'self_develop_ems_detail_model.dart';

class SelfDevelopEmsDetailController extends BaseDetailController {
  DeviceServices deviceServices = Get.find();

  SelfDevelopEmsDetaiModel model = SelfDevelopEmsDetaiModel();

  DeviceModel? deviceModel;
  DeviceItemsGroupModel? groupItems;

  /// 从设备通讯状态展示列表
  List<DetailItemModel> emsItems = [];
  UseSubsribe subsribe = UseSubsribe();
  Map<String, dynamic>? dataSource;
  StreamSubscription<Map<String, dynamic>>? _subscript;
  late Stream<Map<String, dynamic>> broadcastStream;

  /// 主储能ems的设备ID列表
  List<int> salaveEmsIDs = [];

  /// 页面标题
  String title = '';

  /// 当前设备id
  int? deviceId;

  ///
  int? productId;

  /// 产品详情信息
  ProductDetailModel productDetailModel = ProductDetailModel();

  bool isOperateEms = false;

  @override
  void onInit() {
    super.onInit();
    title = Get.arguments['deviceName'];
    deviceId = Get.arguments['deviceId'];
    connectStatus = Get.arguments['connectStatus'];
    productId = Get.arguments['productId'];

    broadcastStream =
        subsribe.start([deviceId!], true).stream.asBroadcastStream();

    _subscript = broadcastStream.listen((data) {
      Map<String, dynamic> periodMap = {};

      for (var i = 0; i < SelfDevelopEmsDetaiModel.timeMap.keys.length; i++) {
        int index = i + 1;
        var field = SelfDevelopEmsDetaiModel.timeMap['time$index'];
        if (data[field?[0]] != null) {
          periodMap.putIfAbsent(
              'period$index',
              () => formateTime(data[field![0]], data[field[1]], data[field[2]],
                  data[field[3]]));
        }
      }
      data.addEntries(periodMap.entries);

      dataSource = data;
      update();
    });

    getEmsDevices().then((value) {
      if (salaveEmsIDs.isEmpty) {
        return;
      }
      UseSocket.getInstance()
        ?..sendMessage(
          RequestMessageType(
            type: MessageEventType.networkStatus,
            data: RequestMessageBody(
              command: RequestCommandEnum.subscribe,
              params: [
                {'device': salaveEmsIDs}
              ],
            ),
          ),
        )
        ..addReceivedMessageCallback(onConnectStatusMessage);
    });
  }

  initData(DeviceModel? device) async {
    deviceModel = device;
    // 初始化数据
    var list = await DeviceFuncUtils.getFormateByDeviceModel([
      model.statusItems,
      emsItems,
    ], deviceModel?.productId);

    groupItems = DeviceItemsGroupModel(
        items: list[0], title: 'siteMonitor.statusInformation'.tr);

    update();
  }

  onConnectStatusMessage(data) {
    if (data['type'] == MessageEventType.networkStatus) {
      var emsDevices = data['data'];
      Map<String, dynamic> emsNetMap = {};
      emsDevices.map((item) => emsNetMap.putIfAbsent(item['deviceId'],
          () => $ConnectStatusTypeEnumMap[item['status'].label]));
      dataSource?.addEntries(emsNetMap.entries);
      update();
    }
  }

  Future getEmsDevices() async {
    try {
      var data = await deviceServices.getEmsDeviceNet({'deviceId': deviceId});
      List<DetailItemModel> itemModels = [];
      for (var i = 0; i < data.length; i++) {
        var slaveEmsNetworkModel = SlaveEmsNetworkModel.fromJson(data[i]);
        salaveEmsIDs.add(slaveEmsNetworkModel.deviceId!);
        itemModels.add(DetailItemModel(
            label:
                '${slaveEmsNetworkModel.deviceName}${ResKey.fromEmsCommunicationStatus.tr}',
            field: slaveEmsNetworkModel.deviceId!.toString()));
      }
      emsItems = itemModels;
      update();
    } on ApiException catch (e) {
      showError(e.message);
    }
  }

  String formateTime(hour1, min1, hour2, min2) {
    var result =
        '${intToString(hour1)}:${intToString(min1)}-${intToString(hour2)}:${intToString(min2)}';
    return result;
  }

  String intToString(value) {
    if (value is int && value < 10) {
      return '0$value';
    } else {
      return value?.toString() ?? '';
    }
  }

  /// 主从设备控制及参数设置功能判断
  bool judgeEsDeviceIsMasterOrSalve(DeviceModel? device) {
    if (device?.masterSlaveMode == MasterSlaveModeType.master ||
        device?.masterSlaveMode == null) {
      return true;
    } else {
      return false;
    }
  }

  /// 操作EMS菜单栏展示与否
  void operateEms() {
    isOperateEms = !isOperateEms;

    update();
  }

  /// 进入EMS远程控制
  void goControlRomote() {
    isOperateEms = false;

    Get.toNamed(
      RouterPath.selfDevelopedEmsRomoteControl,
      arguments: {
        'deviceId': deviceId,
        'connectStatus': connectStatus,
        'productId': productId
      },
    );
    update();
  }

  /// 进入参数配置
  void goSetParams() {
    isOperateEms = false;
    update();

    Get.toNamed(
      RouterPath.selfDevelopedEmsParamsSetting,
      arguments: {
        'deviceId': deviceId,
        'productId': Get.arguments['productId'],
        'connectStatus': connectStatus,
      },
    );
  }

  @override
  void onClose() {
    subsribe.closeListen();
    _subscript?.cancel();
    super.onClose();
  }
}
